package ynu.edu.model.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import ynu.edu.common.domain.PageDTO;
import ynu.edu.common.domain.R;
import ynu.edu.model.domain.HanziGenerationResponse;
import ynu.edu.model.entity.HanziGeneration;
import ynu.edu.model.service.HanziGenerationService;


import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 汉字生成控制器
 */
@Slf4j
@RestController
@RequestMapping("/hanzi")
@RequiredArgsConstructor
@Api(tags = "汉字生成接口")
public class HanziGenerationController {

    private final HanziGenerationService hanziGenerationService;


    /**
     * 更新汉字生成状态
     */
    @PutMapping("/{id}/status")
    @ApiOperation("更新汉字生成状态")
    public R<String> updateStatus(
            @ApiParam(value = "记录ID", required = true)
            @PathVariable Long id,
            @ApiParam(value = "状态", required = true, allowableValues = "processing,success,failed")
            @RequestParam String status,
            @ApiParam(value = "OSS URL")
            @RequestParam(required = false) String ossUrl,
            @ApiParam(value = "生成耗时（毫秒）")
            @RequestParam(required = false) Long generationTime,
            @ApiParam(value = "错误信息")
            @RequestParam(required = false) String errorMessage) {
        
        try {
            boolean result = hanziGenerationService.updateStatus(id, status, ossUrl, generationTime, errorMessage);
            if (result) {
                return R.ok("状态更新成功");
            } else {
                return R.error("状态更新失败，记录可能不存在");
            }
        } catch (Exception e) {
            log.error("状态更新失败", e);
            return R.error("状态更新失败: " + e.getMessage());
        }
    }

    /**
     * 根据汉字字符查询生成记录
     */
    @GetMapping("/char/{chineseChar}")
    @ApiOperation("根据汉字字符查询生成记录")
    public R<List<HanziGenerationResponse>> getByChineseChar(
            @ApiParam(value = "汉字字符", required = true)
            @PathVariable String chineseChar) {
        
        try {
            List<HanziGenerationResponse> records = hanziGenerationService.findByChineseChar(chineseChar);
            return R.ok(records);
        } catch (Exception e) {
            log.error("查询汉字记录失败", e);
            return R.error("查询汉字记录失败: " + e.getMessage());
        }
    }

    /**
     * 根据状态查询生成记录
     */
    @GetMapping("/status/{status}")
    @ApiOperation("根据状态查询生成记录")
    public R<List<HanziGenerationResponse>> getByStatus(
            @ApiParam(value = "状态", required = true, allowableValues = "processing,success,failed")
            @PathVariable String status) {
        
        try {
            List<HanziGenerationResponse> records = hanziGenerationService.findByStatus(status);
            return R.ok(records);
        } catch (Exception e) {
            log.error("查询状态记录失败", e);
            return R.error("查询状态记录失败: " + e.getMessage());
        }
    }

    /**
     * 根据请求ID查询生成记录
     */
    @GetMapping("/request/{requestId}")
    @ApiOperation("根据请求ID查询生成记录")
    public R<HanziGenerationResponse> getByRequestId(
            @ApiParam(value = "请求ID", required = true)
            @PathVariable String requestId) {
        
        try {
            HanziGenerationResponse record = hanziGenerationService.findByRequestId(requestId);
            if (record != null) {
                return R.ok(record);
            } else {
                return R.error("未找到请求ID为 " + requestId + " 的记录");
            }
        } catch (Exception e) {
            log.error("查询请求记录失败", e);
            return R.error("查询请求记录失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询生成记录
     */
    @GetMapping("/page")
    @ApiOperation("分页查询生成记录")
    public R<PageDTO<HanziGeneration>> getPage(
            @ApiParam(value = "页码", required = true, example = "1")
            @RequestParam(defaultValue = "1") int page,
            @ApiParam(value = "每页大小", required = true, example = "10")
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            PageDTO<HanziGeneration> records = hanziGenerationService.getPage(page, size);
            return R.ok(records);
        } catch (Exception e) {
            log.error("分页查询失败", e);
            return R.error("分页查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取统计信息
     */
    @GetMapping("/stats")
    @ApiOperation("获取汉字生成统计信息")
    public R<Map<String, Object>> getStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalRecords", hanziGenerationService.countRecords());
            stats.put("successRecords", hanziGenerationService.countSuccessRecords());
            stats.put("failedRecords", hanziGenerationService.countFailedRecords());
            
            // 计算成功率
            long total = hanziGenerationService.countRecords();
            if (total > 0) {
                double successRate = (double) hanziGenerationService.countSuccessRecords() / total * 100;
                stats.put("successRate", String.format("%.2f%%", successRate));
            } else {
                stats.put("successRate", "0.00%");
            }
            
            return R.ok(stats);
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            return R.error("获取统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有生成记录
     */
    @GetMapping("/list")
    @ApiOperation("获取所有生成记录")
    public R<List<HanziGeneration>> getAllRecords() {
        try {
            List<HanziGeneration> records = hanziGenerationService.list();
            return R.ok(records);
        } catch (Exception e) {
            log.error("获取所有记录失败", e);
            return R.error("获取所有记录失败: " + e.getMessage());
        }
    }

    /**
     * 删除生成记录
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除生成记录")
    public R<String> deleteRecord(
            @ApiParam(value = "记录ID", required = true)
            @PathVariable Long id) {
        
        try {
            boolean result = hanziGenerationService.removeById(id);
            if (result) {
                return R.ok("删除成功");
            } else {
                return R.error("删除失败，记录可能不存在");
            }
        } catch (Exception e) {
            log.error("删除记录失败", e);
            return R.error("删除记录失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除生成记录
     */
    @DeleteMapping("/batch")
    @ApiOperation("批量删除生成记录")
    public R<String> batchDeleteRecords(
            @ApiParam(value = "记录ID列表", required = true)
            @RequestBody List<Long> ids) {
        
        try {
            boolean result = hanziGenerationService.removeByIds(ids);
            if (result) {
                return R.ok("批量删除成功");
            } else {
                return R.error("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除记录失败", e);
            return R.error("批量删除记录失败: " + e.getMessage());
        }
    }
} 